package com.gykfbxxh.imovie.view.main.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.app.utils.util.ToastUtils;
import com.app.utils.util.view.image.CircleImageView;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.adapter.MineGridAdapter;
import com.gykfbxxh.imovie.base.BaseFragment;
import com.gykfbxxh.imovie.bean.film.FilmEntity;
import com.gykfbxxh.imovie.bean.info.UserInfor;
import com.gykfbxxh.imovie.config.ActivityRequestCode;
import com.gykfbxxh.imovie.custom.view.MyGridView;
import com.gykfbxxh.imovie.greendao.GDManager;
import com.gykfbxxh.imovie.manager.UserInforManager;
import com.gykfbxxh.imovie.utils.DialogUtils;
import com.gykfbxxh.imovie.utils.glide.ImageLoader;
import com.gykfbxxh.imovie.view.filmsdetail.acitivity.FilmDetailActivity;
import com.gykfbxxh.imovie.view.main.MainActivity;
import com.gykfbxxh.imovie.view.set.SetActivity;
import com.gykfbxxh.imovie.view.user.activity.LoginActivity;
import com.gykfbxxh.imovie.view.user.activity.MyCollectActivity;
import com.gykfbxxh.imovie.view.user.activity.MyCommentActivity;
import com.gykfbxxh.imovie.view.user.activity.NoticeActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static com.gykfbxxh.imovie.base.BaseActivity.PARAMETER1;

/**
 * Created by xuxinghai
 * On 2017/8/25
 * 我的fragment
 */

public class MineFragment extends BaseFragment implements View.OnClickListener {
    private Activity mActivity;
    private ViewGroup mContentView;//根布局
    private TextView tv_username;
    String mPageName = "MineFragment";
    private MyGridView mGridView;
    private List<FilmEntity> listData = new ArrayList<>() ;
    private MineGridAdapter adapter;
    private CircleImageView civ_author;
    private ScrollView scrollView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(Activity activity) {
        mActivity = activity;
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = (ViewGroup) inflater.inflate(
                    R.layout.fragment_mine_page, null);
            initView();
        }

        return mContentView;
    }


    public void getLikeLookData() {
        if(mGridView==null) {
            return;
        }
        if(adapter==null) {
            adapter = new MineGridAdapter(listData,mActivity,this);
            mGridView.setAdapter(adapter);
        }

        List<FilmEntity> likeDataForMine = GDManager.getInstance().getLikeDataForMine();
        if(likeDataForMine==null||likeDataForMine.size()==0) {
            listData.clear();
            FilmEntity filmEntity = new FilmEntity();
            filmEntity.setIsEmpty("isEmpty");
            listData.add(filmEntity);
            adapter.notifyDataSetChanged();
        }else {
            listData.clear();
            listData.addAll(likeDataForMine);
            FilmEntity filmEntity1 = new FilmEntity();
            filmEntity1.setIsEmpty("isEmpty");
            listData.add(filmEntity1);
            adapter.notifyDataSetChanged();

            mGridView.setFocusable(false);
            scrollView.smoothScrollTo(0,1);
        }

//        if(!UserInforManager.getInstance().isLogin()) {
//            AppConfigTools.TOKENSTR = "";
//            listData.clear();
//            FilmEntity filmEntity = new FilmEntity();
//            filmEntity.setIsEmpty("isEmpty");
//            listData.add(filmEntity);
//            adapter.notifyDataSetChanged();
//            UserInforManager.getInstance().setUserInfor(null);
//            tv_username.setText("登录");
//            return;
//        }
//        if(TextUtils.isEmpty(UserInforManager.getInstance().getUserInfor().getfUsername())) {
//            AppConfigTools.TOKENSTR = "";
//            listData.clear();
//            FilmEntity filmEntity = new FilmEntity();
//            filmEntity.setIsEmpty("isEmpty");
//            listData.add(filmEntity);
//            adapter.notifyDataSetChanged();
//            UserInforManager.getInstance().setUserInfor(null);
//            tv_username.setText("登录");
//            return;
//        }
//        //获取收藏接口数据
//        ParamMap paramMap = new ParamMap();
//        paramMap.put("pno","1");
//        paramMap.put("pagesize","15");
//        paramMap.put("allcount","-1");
//
//        HttpUtils.addPostRequest(URIContant.GETMYCOLLECTLOG, new TypeToken<FilmLikeLookBean>() {
//        }.getType(), mPageName, paramMap, new HttpListener<FilmLikeLookBean>() {
//            @Override
//            public void onError(VolleyError error) {
//                listData.clear();
//                FilmEntity filmEntity = new FilmEntity();
//                filmEntity.setIsEmpty("isEmpty");
//                listData.add(filmEntity);
//                adapter.notifyDataSetChanged();
//            }
//
//            @Override
//            public void onSuccess(FilmLikeLookBean response) {
//                listData.clear();
//                if(response!=null&&response.getResult()!=null) {
//                    FilmLikeLookBean.ResultBean result = response.getResult();
//                    if(result.getList()!=null) {
//                        List<FilmLikeLookBean.ResultBean.FilmLikeLookData> list = result.getList();
//                        if(list!=null&&list.size()>0) {
//                            for (int i = 0;i<list.size();i++){
//                                FilmEntity filmEntity = list.get(i).getfObject();
//                                filmEntity.setIsEmpty("");
//                                listData.add(filmEntity);
//                            }
//                        }
//                    }
//                }
//                FilmEntity filmEntity1 = new FilmEntity();
//                filmEntity1.setIsEmpty("isEmpty");
//                listData.add(filmEntity1);
//                adapter.notifyDataSetChanged();
//
//                mGridView.setFocusable(false);
//                scrollView.smoothScrollTo(0,1);
//            }
//        });
    }

    private LinearLayout ll_userview;
    private RelativeLayout rl_notice ,rl_mycomment,rl_mycollect;
    /**
     * 初始化layout控件
     */
    private void initView() {
        scrollView = (ScrollView) mContentView.findViewById(R.id.scrollView);
        civ_author = (CircleImageView) mContentView.findViewById(R.id.civ_author);
        tv_username = (TextView) mContentView.findViewById(R.id.tv_username);
        ll_userview = (LinearLayout) mContentView.findViewById(R.id.ll_userview);
        rl_notice = (RelativeLayout) mContentView.findViewById(R.id.rl_notice);
        rl_mycomment = (RelativeLayout) mContentView.findViewById(R.id.rl_mycomment);
        rl_mycollect = (RelativeLayout) mContentView.findViewById(R.id.rl_mycollect);
        mGridView = (MyGridView) mContentView.findViewById(R.id.mGridView);
        ll_userview.setOnClickListener(this);
        rl_notice.setOnClickListener(this);
        rl_mycomment.setOnClickListener(this);
        rl_mycollect.setOnClickListener(this);
        if(adapter==null) {
            adapter = new MineGridAdapter(listData,mActivity,this);
            mGridView.setAdapter(adapter);
        }
        refreshUserData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_userview:
                if(UserInforManager.getInstance().isLogin()) {
                    Intent intent1 = new Intent(mActivity, SetActivity.class);
                    startActivityForResult(intent1,ActivityRequestCode.REQEUST_CODE_SET);
                }else {
                    Intent intent1 = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent1,ActivityRequestCode.REQEUST_CODE_SET);
                }
                break;
            case R.id.rl_notice://我的消息
                if(UserInforManager.getInstance().isLogin()) {
                    Intent intentn = new Intent(mActivity, NoticeActivity.class);
                    startActivity(intentn);
                }else {
                    ToastUtils.makeText("请先登录!");
                }
                break;
            case R.id.rl_mycomment://我的评论
                if(UserInforManager.getInstance().isLogin()) {
                    Intent intentn = new Intent(mActivity, MyCommentActivity.class);
                    startActivity(intentn);
                }else {
                    ToastUtils.makeText("请先登录!");
                }
                break;
            case R.id.rl_mycollect://我的收藏
                if(UserInforManager.getInstance().isLogin()) {
                    Intent intentn = new Intent(mActivity, MyCollectActivity.class);
                    startActivity(intentn);
                }else {
                    ToastUtils.makeText("请先登录!");
                }
                break;
            case R.id.iv_imageview_empty:
                ((MainActivity)mActivity).goToFilmLibrary();
                break;
            case R.id.iv_imageview:
                FilmEntity filmEntity1 = (FilmEntity) v.getTag(R.id.tag_first);
                if(filmEntity1==null) {
                    return;
                }
                Intent intent = new Intent(mActivity, FilmDetailActivity.class);
                intent.putExtra(PARAMETER1,filmEntity1.getFId());
                startActivity(intent);
                break;
            case R.id.iv_right_top:
                final FilmEntity filmEntity = (FilmEntity) v.getTag(R.id.tag_first);
                final int position = (int) v.getTag(R.id.tag_secong);
                HashMap<String, String> style = new HashMap<>();
                style.put("title", "提示");
                style.put("desc", "你确定要删除:"+ filmEntity.getFName()+"?");
                style.put("btnPosi", "确定");
                style.put("btnNega", "取消");

                DialogUtils.getInstance().setOnDialogBtnClick(new DialogUtils.OnDialogBtnClickListener() {
                    @Override
                    public void onPositiveClick() {
                        removeLikeData(filmEntity.getFId(),position);
                    }

                    @Override
                    public void onNegativeClick() {

                    }
                });
                DialogUtils.getInstance().showCustomDialog(mActivity, style);
                break;
        }
    }

    private void removeLikeData(String fId, final int position) {
        GDManager.getInstance().delLikeLookData(fId);
        listData.remove(position);
        adapter.notifyDataSetChanged();
        ToastUtils.makeText("删除成功");
//        ParamMap paramMap = new ParamMap();
//        paramMap.put("objectid",fId);
//        HttpUtils.ParmsMapMD5(paramMap);
//        HttpUtils.addPostRequest(URIContant.DELCOLLECTLOGBYOBJECTID,new TypeToken<DataBean>(){}.getType(),  mPageName, paramMap, new HttpListener<DataBean>() {
//            @Override
//            public void onError(VolleyError error) {
//                ToastUtils.makeText("删除失败");
//            }
//
//            @Override
//            public void onSuccess(DataBean response) {
//                if(response.noError()) {
//                    listData.remove(position);
//                    adapter.notifyDataSetChanged();
//                    ToastUtils.makeText("删除成功");
//                }
//            }
//        });
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ActivityRequestCode.REQEUST_CODE_SET) {
            if (resultCode == RESULT_OK ) {
                refreshUserData();
            }
        }
    }

    public void refreshUserData() {
        if(UserInforManager.getInstance().isLogin()) {
            updateUserInfo();
        }else {
            tv_username.setText("登录");
            civ_author.setImageResource(R.drawable.g_header);
        }
        getLikeLookData();

    }

    private void updateUserInfo() {
        UserInfor userInfor = UserInforManager.getInstance().getUserInfor();
        ImageLoader.getInstance().loadSmallImage2Cache(mActivity,civ_author,userInfor.getfPhoto());
        tv_username.setText(userInfor.getfUsername());
    }
}
